package com.nio.charset.charset;

import org.junit.Test;

import java.io.*;
import java.nio.charset.Charset;

/**
 * 主要用来观察字符编码的几个类
 * Created by yangliwei on 2017/10/15.
 */
public class FirstTest {

    //编码 字符->字节 encode
    //解码 字节->字符 decode
    @Test
    public void test01() throws UnsupportedEncodingException {
        System.out.println("系统自带的字符编码\n"+System.getProperty("file.encoding"));
        System.out.println(Charset.defaultCharset());
        String str = "这是一个中文字符";
        //编码
        byte[] sb = str.getBytes();
        //解码
        String as = new String(sb,"UTF-8");
        System.out.println(as);

    }

    //测试Charset里面简单的方法
    @Test
    public void testSimpleMethod(){
        System.out.println(Charset.defaultCharset().name());
        for(String str :Charset.defaultCharset().aliases()){
            System.out.println(str);
        }
    }


    /**
     * 生成两种编码的文件
     * 然后用notepad++ 插件 HEX-editor打开
     * d6 d0 ce c4              gbk
     * e4 b8 ad e6 96 87        utf-8
     */
    @Test
    public void testTwoCharset() throws IOException {
//        String projectPath = ClassLoader.getSystemClassLoader().getResource(".").getPath();//  /D:/ideaproject1/javastudy/out/production/javastudy/

        String projectPath = System.getProperty("user.dir");//D:\ideaproject1\javastudy
        String filePath=projectPath+File.separator+"test"+File.separator;
        System.out.println(filePath);
        File dir = new File(filePath);
        if(!dir.exists()){
            dir.mkdirs();
        }

        String utf8Path = filePath + "utf.txt";
        String data = "中文";
        OutputStreamWriter osw = null;
        osw = new OutputStreamWriter(new FileOutputStream(utf8Path), "UTF-8");
        osw.write(data);
        osw.flush();

        String gbkPath = filePath + "gbk.txt";
        osw = new OutputStreamWriter(new FileOutputStream(gbkPath), "GBK");
        osw.write(data);
        osw.flush();

    }
}
